//
//  ListController.swift
//  hello
//
//  Created by yafei li on 2025/10/9.
//


import Vapor
import Fluent
import JWT


struct ListController: RouteCollection {
    func boot(routes: any Vapor.RoutesBuilder) throws {
        // 基础路径为 "/lists"
        let lists = routes.grouped("api", "lists")
        
        //私有路由（需要 JWT 认证）
        let protected = lists.grouped(UserAuthenticator(), UserPayload.guardMiddleware())
        
        // 用户相关操作
        registerListsRoutes(lists: protected)
    }
}

extension ListController {
    
    //    注册相关操作路由
    func registerListsRoutes(lists:  any RoutesBuilder) {
        lists.get("getAllLists",use: getAllLists)
        lists.get("getListsPage", use: getListsPage)
        lists.post("createListItem", use: createListItem) // 添加插入数据的路由
    }
    
    // 获取所有数据
    func getAllLists(req: Request) async throws -> ApiResponse<[ListItemDTO]> {
        do {
            let lists = try await ListItem.query(on: req.db).all()
            return ApiResponse.success(data: lists.map { $0.toDTO() })
        } catch  {
            return ApiResponse.success(data: [])
        }
    }

    // 分页获取数据
    func getListsPage(req: Request) async throws -> PaginatedApiResponse<ListItemDTO> {
        // 获取查询参数，设置默认值
        let page = req.query[Int.self, at: "page"] ?? 1
        let pageSize = req.query[Int.self, at: "pageSize"] ?? 10
        let keyword = req.query[String.self, at: "keyword"] ?? ""
        
        // 确保页码和页大小为正整数
        guard page > 0, pageSize > 0 else {
            throw Abort.requestParametersError
        }
        
        let query =  ListItem.query(on: req.db).filter(\.$random == keyword)
        
        // 获取总记录数
        let total = try await query.count()
        
        // 计算偏移量并查询分页数据
        let lists = try await query.offset((page - 1) * pageSize)
            .limit(pageSize)
            .all()
        
        // 转换为DTO并返回分页响应
        return PaginatedApiResponse.success(
            data: lists.map { $0.toDTO() },
            total: total,
            page: page,
            size: pageSize,
            message: "获取成功"
        )
    }
    
    // 插入数据
    func createListItem(req: Request) async throws -> ApiResponse<ListItemDTO> {
        // 解码请求体数据
        let createRequest = try req.content.decode(ListItemDTO.self)
        
        // 验证参数
        guard !createRequest.random.isEmpty else {
            throw Abort.requestParametersError
        }
        
        // 创建ListItem实例
        let newListItem = try ListItem(random: createRequest.random)
        
        // 保存到数据库
        try await newListItem.save(on: req.db)
        
        // 返回创建成功的响应
        return ApiResponse.success()
    }
}